﻿using GatewayClient.Device;
using GatewayClient.MQ;
using Iot.Device.Gpio.Drivers;
using IotDeviceToolHepler.Model.Constant;
using IotDeviceToolHepler.Utils;
using IotDeviceToolHepler.WiringOPSharp;
using Models.Common;
using Models.Device;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Device.Gpio;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UtilsBase;
using UtilsCache;
using static Models.Common.EnumDeviceType;

namespace GatewayClient.Orangepi
{
    public class OrangePIGpioValueChange
    {
        // public object setValue = null;
        //  public string methodName = "";

        public void eventCallbackByGpio(object obj)
        {
            MQReqModel<object> mQReqModel = (MQReqModel<object>)obj;
            CommandLogModel commandLogModel = mQReqModel.toGatewayData;

            ModelCommandAgreement modelCommandAgreement = JsonConvert.DeserializeObject<ModelCommandAgreement>(commandLogModel.parameter);

            List<ModelCommandAgreementParameterCommand> commandList = UtilsObject.DynamicToEntity<List<ModelCommandAgreementParameterCommand>>(modelCommandAgreement.agreementParameter.command);
            ModelCommandAgreementParameter modelCommandAgreementGpio = UtilsObject.DynamicToEntity<ModelCommandAgreementParameter>(modelCommandAgreement.agreementParameter);
            ModelCommandAgreementParameterCommand command = commandList.Where(c => c.key == commandLogModel.key).FirstOrDefault();
            //开high 和//开low 只能二选一，不能同时有

            string state = command.callBackKey;
            int callBackRunInterval = command.callBackRunInterval;
            int wpi = modelCommandAgreementGpio.wpi;
            try
            {
                //判断是否重复
                string runing = UtilMemoryCacheHelper.get<string>("callBackByGpioValueChange" + wpi.ToString() + state);
                if (runing != null)
                {
                    return;
                }
                UtilMemoryCacheHelper.set("callBackByGpioValueChange" + wpi.ToString() + state, "true");


                bool hasStatusChange = false;//条件改变> 、 <,,true满足当前要求的条件，false不满足当前监听条件
                string gpioStatus = "";
                bool doublecheck = false;
                string check_state = "";
                while (true)
                {

                    //判断
                    string isRuning = UtilMemoryCacheHelper.get<string>("callBackByGpioValueChange" + wpi.ToString() + state);
                    if (string.IsNullOrEmpty(isRuning))
                    {
                        //已经删除，退出
                        break;
                    }

                    check_state = UtilsOrangePiGpio.getGpioInputMode(wpi);

                    //if (state == "open" || state == "close")
                    //{
                    //    if (state == check_state && hasStatusChange == false)
                    //    {
                    //        hasStatusChange = true;
                    //        //Console.WriteLine("+++++++++++++ 回调pinNum+++++++++++ " + check_state + "-" + System.DateTime.Now);
                    //        //如果==要触发的值，和上一次的值不一样执行回调
                    //        returnGpioValueChange(mQReqModel, state);
                    //    }
                    //    if (state != check_state)
                    //    {
                    //        hasStatusChange = false;
                    //    }
                    //}
                    //else if (state == "openclose")
                    //{
                    //监听开或关变化
                    if (gpioStatus != check_state)
                    {
                        if (doublecheck == false)
                        {
                            doublecheck = true;
                            continue;
                        }

                        gpioStatus = check_state;
                        //hasStatusChange = false;
                        //Console.WriteLine("+++++++++++++ 回调pinNum+++++++++++ " + check_state + "-" + System.DateTime.Now);
                        //如果==要触发的值，和上一次的值不一样执行回调

                        if (state == "open" || state == "close")
                        {
                            if (state == gpioStatus)
                            {
                                returnGpioValueChange(mQReqModel, gpioStatus);
                                doublecheck = false;
                            }
                        }
                        else if (state == "openclose")
                        {
                            returnGpioValueChange(mQReqModel, gpioStatus);
                            doublecheck = false;
                        }


                    }
                    //if (gpioStatus == check_state)
                    //{
                    //    hasStatusChange = true;
                    //}
                    //}

                    Thread.Sleep(callBackRunInterval);
                }
            }
            catch (Exception ex)
            {
                //删除运行标识
                UtilMemoryCacheHelper.remove("callBackByGpioValueChange" + wpi.ToString() + state);

                ModelReceverData modelDeviceData = new ModelReceverData();
                modelDeviceData.content = ex.ToString();
                mQReqModel.respCode = ResponseCode.System_ERROR;
                mQReqModel.respMsg = MQEventEnum.Event_State_Error;
                mQReqModel.toServerData = modelDeviceData;
                new ServiceMQ_Helper().sendMsg(mQReqModel);
                Console.WriteLine(ex.Message);
            }
        }
        public void returnGpioValueChange(object obj, string content)
        {
            MQReqModel<object> mQReqModel = (MQReqModel<object>)obj;
            CommandLogModel commandLogModel = mQReqModel.toGatewayData;

            Console.WriteLine(" gpio 回调 " + DateTime.Now);
            ModelReceverData modelDeviceData = new ModelReceverData();
            modelDeviceData.content = content;
            mQReqModel.toServerData = modelDeviceData;
            new ServiceMQ_Helper().sendMsg(mQReqModel);
        }

        public void returnGpioValueChangeStop(object obj)
        {
            MQReqModel<object> mQReqModel = (MQReqModel<object>)obj;
            try
            {
                CommandLogModel commandLogModel = mQReqModel.toGatewayData;
                ModelCommandAgreement modelCommandAgreement = JsonConvert.DeserializeObject<ModelCommandAgreement>(commandLogModel.parameter);



                List<ModelCommandAgreementParameterCommand> commandList = UtilsObject.DynamicToEntity<List<ModelCommandAgreementParameterCommand>>(modelCommandAgreement.agreementParameter.command);
                ModelCommandAgreementParameter modelCommandAgreementGpio = UtilsObject.DynamicToEntity<ModelCommandAgreementParameter>(modelCommandAgreement.agreementParameter);
                ModelCommandAgreementParameterCommand command = commandList.Where(c => c.key == commandLogModel.key).FirstOrDefault();
                //开high 和//开low 只能二选一，不能同时有

                string state = command.callBackKey;
                int wpi = modelCommandAgreementGpio.wpi;
                UtilMemoryCacheHelper.remove("callBackByGpioValueChange" + wpi.ToString() + state);
                Console.WriteLine(" gpio 回调停止 " + DateTime.Now);
            }
            catch (Exception ex)
            {
                ModelReceverData modelDeviceData = new ModelReceverData();
                modelDeviceData.content = ex.ToString();
                mQReqModel.respCode = ResponseCode.System_ERROR;
                mQReqModel.respMsg = MQEventEnum.Event_State_Error;
                mQReqModel.toServerData = modelDeviceData;
                new ServiceMQ_Helper().sendMsg(mQReqModel);
                Console.WriteLine(ex.ToString());
            }
        }
    }
}
